const db = wx.cloud.database();
const _ = db.command;
const userService = require('./userService');

/**
 * 获取发现页分享的菜品列表
 * @param {Object} options 查询参数
 * @returns {Promise<Array>} 菜品列表
 */
const getSharedDishes = async (options = {}) => {
  try {
    const {
      category = '',      // 分类
      keyword = '',       // 搜索关键词
      orderBy = 'time',   // 排序字段：likes-点赞量，time-时间
      limit = 10,         // 每页数量
      skip = 0,           // 跳过的数量
    } = options;
    
    // 获取分享表中的菜品数据
    const shareRes = await db.collection('Share').where({
      dishId: _.exists(true)
    }).orderBy('shareTime', 'desc')
      .skip(skip)
      .limit(limit)
      .get();
    
    // 如果没有分享记录，直接返回空数组
    if (shareRes.data.length === 0) {
      return [];
    }
    
    // 获取菜品详情
    const dishes = [];
    for (const share of shareRes.data) {
      try {
        // 尝试获取菜品信息
        let dish = null;
        try {
          const dishRes = await db.collection('mydishes').doc(share.dishId).get();
          dish = dishRes.data;
        } catch (err) {
          console.error('获取菜品详情失败:', err);
          // 使用分享表中的基本信息
          dish = {
            _id: share.dishId,
            name: share.dishName || '未知菜品',
            image: share.dishImage || '',
            description: ''
          };
        }
        
        // 检查是否符合搜索条件
        if (keyword && !dish.name.includes(keyword)) {
          continue;
        }
        
        if (category && category !== 'all' && dish.category !== category) {
          continue;
        }
        
        // 获取用户信息（直接从Share表中获取）
        const userInfo = {
          _id: share.userId,
          nickName: share.userName || '用户',
          avatarUrl: share.userAvatar || ''
        };
        
        // 添加到结果列表
        dishes.push({
          ...dish,
          shareInfo: {
            shareTime: share.shareTime,
            userId: share.userId,
            kitchenId: share.kitchenId
          },
          userInfo: userInfo
        });
      } catch (err) {
        console.error('处理分享菜品数据失败:', err);
      }
    }
    
    // 根据排序字段排序
    if (orderBy === 'likes') {
      dishes.sort((a, b) => (b.likeCount || 0) - (a.likeCount || 0));
    }
    
    return dishes;
  } catch (error) {
    console.error('获取分享菜品失败:', error);
    return [];
  }
};

/**
 * 获取发现页分享的厨房列表
 * @param {Object} options 查询参数
 * @returns {Promise<Array>} 厨房列表
 */
const getSharedKitchens = async (options = {}) => {
  try {
    const {
      keyword = '',       // 搜索关键词
      orderBy = 'time',   // 排序字段：likes-点赞量，time-时间
      limit = 10,         // 每页数量
      skip = 0,           // 跳过的数量
    } = options;
    
    // 获取分享表中的厨房数据（只筛选包含kitchenId但没有dishId的记录）
    const shareRes = await db.collection('Share')
      .where({
        kitchenId: _.exists(true),
        dishId: _.exists(false)
      })
      .orderBy('shareTime', 'desc')
      .skip(skip)
      .limit(limit)
      .get();
    
    // 如果没有分享记录，直接返回空数组
    if (shareRes.data.length === 0) {
      return [];
    }
    
    // 获取厨房详情
    const kitchens = [];
    for (const share of shareRes.data) {
      try {
        // 尝试获取厨房信息
        let kitchen = null;
        try {
          const kitchenRes = await db.collection('mykichen').doc(share.kitchenId).get();
          kitchen = kitchenRes.data;
        } catch (err) {
          console.error('获取厨房详情失败:', err);
          // 使用分享表中的基本信息
          kitchen = {
            _id: share.kitchenId,
            name: share.kitchenName || '未知厨房',
            image: share.kitchenImage || '',
            description: ''
          };
        }
        
        // 检查是否符合搜索条件
        if (keyword && !kitchen.name.includes(keyword)) {
          continue;
        }
        
        // 获取用户信息（直接从Share表中获取）
        const userInfo = {
          _id: share.userId,
          nickName: share.userName || '用户',
          avatarUrl: share.userAvatar || ''
        };
        
        // 添加到结果列表
        kitchens.push({
          ...kitchen,
          shareInfo: {
            shareTime: share.shareTime,
            userId: share.userId
          },
          userInfo: userInfo
        });
      } catch (err) {
        console.error('处理分享厨房数据失败:', err);
      }
    }
    
    // 根据排序字段排序
    if (orderBy === 'likes') {
      kitchens.sort((a, b) => (b.likeCount || 0) - (a.likeCount || 0));
    }
    
    return kitchens;
  } catch (error) {
    console.error('获取分享厨房失败:', error);
    return [];
  }
};

/**
 * 点赞菜品
 * @param {string} dishId 菜品ID
 * @param {string} kitchenId 厨房ID
 * @returns {Promise<boolean>} 是否点赞成功
 */
const likeDish = async (dishId, kitchenId) => {
  try {
    const userId = userService.getCurrentUserId();
    if (!userId || !dishId) return false;
    
    // 查询是否已点赞
    const likesCollection = db.collection('Like');
    const hasLiked = await likesCollection.where({
      userId,
      dishId
    }).count();
    
    // 如果已点赞，则取消点赞
    if (hasLiked.total > 0) {
      await likesCollection.where({
        userId,
        dishId
      }).remove();
      
      // 更新菜品点赞数
      await db.collection('mydishes').doc(dishId).update({
        data: {
          likeCount: _.inc(-1)
        }
      });
      // 更新share表点赞数
      await db.collection('Share')
            .where(
              _.or([
                { kitchenId: kitchenId },
                { dishId: dishId }
            ]))
           .update({
                data: {
                    likeCount: _.inc(-1)
                }
            });
      
      return false; // 返回当前点赞状态
    } 
    // 否则添加点赞
    else {
      await likesCollection.add({
        data: {
          userId,
          dishId,
          createTime: db.serverDate()
        }
      });
      
      // 更新菜品点赞数
      await db.collection('mydishes').doc(dishId).update({
        data: {
          likeCount: _.inc(1)
        }
      });
      // 更新share表点赞数
      await db.collection('Share')
           .where(
            _.or([
              { kitchenId: kitchenId },
              { dishId: dishId }
          ]))
           .update({
                data: {
                    likeCount: _.inc(1)
                }
            });
      return true; // 返回当前点赞状态
    }
  } catch (error) {
    console.error('点赞操作失败:', error);
    return null;
  }
};

/**
 * 收藏菜品
 * @param {string} dishId 菜品ID
 * @param {string} kitchenId 厨房ID
 * @returns {Promise<boolean>} 是否收藏成功
 */
const favoriteDish = async (dishId, kitchenId) => {
  try {
    const userId = userService.getCurrentUserId();
    if (!userId || !dishId) return false;
    
    // 获取收藏
    const favorites = wx.getStorageSync('favorites') || [];
    
    // 查找是否已收藏
    const index = favorites.findIndex(fav => 
      fav.dishId === dishId && fav.kitchenId === kitchenId
    );
    
    // 如果已收藏，则取消收藏
    if (index !== -1) {
      favorites.splice(index, 1);
      wx.setStorageSync('favorites', favorites);
      return false; // 返回当前收藏状态
    } 
    // 否则添加收藏
    else {
      favorites.push({
        userId,
        dishId,
        kitchenId,
        timestamp: new Date().getTime()
      });
      wx.setStorageSync('favorites', favorites);
      return true; // 返回当前收藏状态
    }
  } catch (error) {
    console.error('收藏操作失败:', error);
    return null;
  }
};

/**
 * 添加评论
 * @param {string} dishId 菜品ID
 * @param {string} content 评论内容
 * @param {string} kitchenId 厨房ID
 * @returns {Promise<Object>} 评论结果
 */
const addComment = async (dishId, content, kitchenId) => {
  try {
    const userId = userService.getCurrentUserId();
    if (!userId || !dishId || !content) return null;
    
    // 添加评论
    const commentCollection = db.collection('Comment');
    const result = await commentCollection.add({
      data: {
        userId,
        dishId,
        content,
        likeCount: 0,
        createTime: db.serverDate()
      }
    });
    
    // 更新菜品评论数
    await db.collection('mydishes').doc(dishId).update({
      data: {
        commentCount: _.inc(1)
      }
    });
    // 更新share表评论数
    await db.collection('Share')
            .where(
              _.or([
                { kitchenId: kitchenId },
                { dishId: dishId }
            ]))
           .update({
                data: {
                    commentCount: _.inc(1)
                }
            });
    // 获取用户信息
    const userInfo = await userService.getUserInfo(userId);
    
    return {
      _id: result._id,
      userId,
      dishId,
      content,
      likeCount: 0,
      createTime: new Date(),
      userInfo
    };
  } catch (error) {
    console.error('添加评论失败:', error);
    return null;
  }
};

/**
 * 获取评论列表
 * @param {string} dishId 菜品ID
 * @param {number} limit 每页数量
 * @param {number} skip 跳过的数量
 * @returns {Promise<Array>} 评论列表
 */
const getComments = async (dishId, limit = 10, skip = 0) => {
  try {
    if (!dishId) return [];
    
    // 获取评论
    const commentCollection = db.collection('Comment');
    const res = await commentCollection
      .where({ dishId })
      .orderBy('createTime', 'desc')
      .skip(skip)
      .limit(limit)
      .get();
    
    // 查询用户信息
    const comments = res.data;
    const userIds = [...new Set(comments.map(comment => comment.userId))];
    
    // 获取用户信息
    const userInfos = {};
    for (const userId of userIds) {
      const userInfo = await userService.getUserInfo(userId);
      userInfos[userId] = userInfo;
    }
    
    // 组合评论和用户信息
    return comments.map(comment => ({
      ...comment,
      userInfo: userInfos[comment.userId] || null
    }));
  } catch (error) {
    console.error('获取评论失败:', error);
    return [];
  }
};

// 导出方法
module.exports = {
  getSharedDishes,
  getSharedKitchens,
  likeDish,
  favoriteDish,
  addComment,
  getComments
}; 